﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;

namespace Utilities.General.Message.Push.Mail
{
    public class MailPush : Push
    {
        protected string sendUserMail;
        protected string sendUserName;
        protected string sendUserPWD;
        protected string smtpHost;
        protected int smtpPort;
        public MailPush()
        {
            //Config
            config = "";
        }
        public override bool Send(MsgArgs args)
        {
            bool result = false;
            result = SendMailBySmtp(args.RecvUsers, args.CCUsers, args.Body.Subject, args.Body.Body);
            if (result)
            {
                //发送完成事件触发
                if (OnSendComplete != null)
                {
                    PushArgs e = new PushArgs();
                    e.data = args;
                    OnSendComplete(this, e);
                }
            }
            return result;
        }

        protected bool SendMailBySmtp(IList<string> recvusers, IList<string> ccuser, string subject, string body)
        {
            try
            {
                MailMessage mail = new MailMessage();
                mail.From = new MailAddress(this.sendUserMail);
                foreach (string p in recvusers)
                    mail.To.Add(p);
                foreach (string cc in ccuser)
                    mail.CC.Add(cc);
                mail.Subject = subject;
                mail.Body = body;
                SmtpClient send = new SmtpClient();
                send.Host = this.smtpHost;
                send.Port = this.smtpPort;
                send.Credentials = new NetworkCredential(this.sendUserName, this.sendUserPWD);
                send.Send(mail);
                send.Dispose();
                return true;
            }
            catch (Exception e)
            {
                log.error(e);
                return false;
            }
        }
    }
}
